import React, { Component } from "react";
import Modal from 'bee-modal';
import axios from 'axios';
import 'bee-modal/build/Modal.css';
import Table from "bee-table";
import 'bee-table/build/Table.css';
import multiSelect from "bee-table/build/lib/multiSelect";
import { Upload, Button, Checkbox, Radio, Icon, ProgressBar } from "tinper-bee";
import './index.less';
import selfNaxios from 'utils/ajaxConfig.js';
import { vendorsDanger } from 'utils/config.js';
const Dragger = Upload.Dragger;
let expiresTime = 0;
let aliyunoss = {};
let fileChangeTimer;

function getosssignForPost(param) {
    return axios({
        method: 'get',
        url: '/oss/signForPost',
        params: param,
        headers: {
            'Cache-Control': 'no-cache'
        }
    })
}

function uploadFile(param, success, error) {
    return selfNaxios({
        method: 'post',
        url: '/picture/upload',
        data: param
    }, success, error)
}

function getFileList(param, success, error) {
    return selfNaxios({
        method: 'get',
        url: '/picture/query',
        params: param
    }, success, error)
}

function deleteFile(param, success, error) {
    return selfNaxios({
        method: 'get',
        url: '/picture/delete',
        params: param
    }, success, error)
}

function downloadFile(param, success, error) {
    return selfNaxios({
        method: 'get',
        url: '/file/download',
        params: param,
    }, success, error);
}

function downloadIamge(url, name) {//下载图片地址和图片名
    let image = new Image();
    // 解决跨域 Canvas 污染问题
    image.setAttribute("crossOrigin", "anonymous");
    image.onload = function () {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
        let a = document.createElement("a"); // 生成一个a元素
        let event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name;
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
    };
    image.src = url;
}


function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function guid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

class YGCCreateUpload extends Component {
    constructor(props) {
        super(props);
        let _me = this;
        this.state = {
            isShow: false,
            action: '',
            uploadInfoData: {},
            fileList: [
            ],
        };
        this.uploadProps = {
            name: 'file',
            multiple: true,
            showUploadList: false,
            size: 1024000,
            // accept:props.accept||
            headers: {
            },
            onChange(info) {
                clearTimeout(fileChangeTimer);
                fileChangeTimer = setTimeout(() => {
                    let fileList = info.fileList;
                    let map = new Map();
                    fileList.forEach(file => {
                        map.set(file.uid, file);
                    });
                    _me.setState((state) => {
                        state.fileList.forEach(cur => {
                            if (cur.submit) {
                                return;
                            }
                            if (map.has(cur.uid)) {
                                let preStatus = cur.status;
                                let mapItem = map.get(cur.uid);
                                cur.percent = mapItem.percent;
                                cur.status = mapItem.status;
                                if (cur.status == 'done' && preStatus != cur.status) {
                                    uploadFile({
                                        "pkBill": _me.props.pkBill,
                                        "pkProject": _me.props.pkProject,
                                        "billType": _me.props.billType,
                                        "pictures": [cur.key]

                                    }, (res) => {
                                        if (res.data.resultCode != 'busi_ex') {
                                            let result = res.data.result[0];
                                            _me.setState(state => {
                                                let fileList = state.fileList;
                                                fileList.forEach(item => {
                                                    if (item == cur) {
                                                        let name = item.name;
                                                        Object.assign(item, result, { submit: true, name });

                                                    }
                                                })
                                                return {
                                                    fileList
                                                }
                                            });
                                        } else {
                                            vendorsDanger({ text: res.data.exMsg });
                                            _me.setState(state => {
                                                let fileList = state.fileList;
                                                for (let i = 0; i < fileList.length; i++) {
                                                    if (cur == fileList[i]) {
                                                        fileList.splice(i, 1);
                                                        break;
                                                    }
                                                }
                                                return {
                                                    fileList
                                                }
                                            });
                                        }
                                    }, (error) => {
                                        console.error(error);
                                    })

                                }
                            }
                        })
                        return {
                            fileList: state.fileList,
                        }
                    })
                }, 500);

            },
            beforeUpload: function (file) {
                // let suffixtest = /(doc|docx|xls|xlsx|pdf)$/i;
                // if (file.size / 1024 / 1024 > 5 || !suffixtest.test(file.name)) {
                //     vendorsDanger({ text: "只能上传word、excel和pdf文件,最大5MB。" });
                //     return false;
                // }
                return new Promise((resolve, reject) => {
                    if (new Date().getTime() + 10000 >= expiresTime * 1000) {
                        getosssignForPost({ ieStamp: new Date().getTime(), isAjax: 1 }).then((res) => {
                            let data = res.data;
                            if (data.resultCode == "ok") {
                                aliyunoss = data.result;
                                expiresTime = aliyunoss.expire;
                                let filename = file.name;
                                let key = aliyunoss.dir + (_me.props.billType) + guid() + '/' + filename;
                                let fileList = [..._me.state.fileList];
                                fileList.push({
                                    status: 'loading',
                                    uid: file.uid,
                                    name: filename,
                                    percent: 0,
                                    key,
                                })
                                _me.setState({
                                    action: aliyunoss.host,
                                    uploadInfoData: {
                                        policy: aliyunoss.policy,
                                        signature: aliyunoss.signature,
                                        OSSAccessKeyId: aliyunoss.accessKeyId,
                                        success_action_status: 200,
                                        key,
                                    },
                                    fileList,
                                }, () => {
                                    resolve();
                                })
                            }
                        }).catch(error => {
                            reject();
                        });
                    } else {
                        _me.setState((prestate) => {
                            let uploadInfoData = prestate.uploadInfoData;
                            let filename = file.name;
                            let key = aliyunoss.dir + (_me.props.billType) + guid() + '/' + filename;
                            uploadInfoData.key = key;
                            uploadInfoData.name = filename;
                            let fileList = [..._me.state.fileList];
                            fileList.push({
                                status: 'loading',
                                uid: file.uid,
                                name: filename,
                                percent: 0,
                                key,
                            })
                            return {
                                uploadInfoData,
                                fileList,
                            }
                        }, () => {
                            resolve();
                        })
                    }
                }).then(cur => {

                }).catch(cur => {

                })
            }
        };
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        if (prevState.isShow && !this.state.isShow) {
            this.setState({
                fileList: [],
            });
        }
        if (!prevState.isShow && this.state.isShow) {
            getFileList({
                pkBill: this.props.pkBill,
            },
                (res) => {
                    let fileList = res.data.result || [];
                    fileList.forEach(cur => {
                        //snapshotUrl  origUrl   type   name
                        cur.uid = cur.name;
                        cur.key = cur.name;
                        cur.percent = 100;
                        cur.submit = true;
                        cur.name = cur.name.substr(cur.name.lastIndexOf('/') + 1);
                        cur.status = 'done';
                    })
                    this.setState({
                        fileList
                    })
                },
                (error) => {

                }
            );
        }
    }

    open = () => {
        this.setState({
            isShow: true,
        })
    }

    closeUpload = () => {
        this.setState({
            isShow: false,
        })
    }

    cancelClick = (record) => {
        let fileList = this.state.fileList.filter(cur => {
            return cur.uid !== record.uid
        })
        this.setState({
            fileList,
        })
        if (record.submit) {
            deleteFile({
                pkBill: this.props.pkBill,
                picName: record.uid,
            },
                (res) => {
                    console.log('delete success');
                },
                (error) => {
                    console.log('delete error');
                }
            );
        }
    }

    downloadClick = (record) => {
        downloadFile({ ossName: record.key },
            (response) => {
                if (response.data.resultCode != 'busi_ex') {
                    let url = response.data.result;
                    let fileMatches = decodeURI(url).match(/\/([^/]*)\.(\w*)\?/);
                    let fileType = fileMatches[2].toUpperCase();
                    let fileName = fileMatches[1];
                    if (['PNG', 'BMP', 'JPG', 'JPEG', 'PNG', 'GIF'].indexOf(fileType) != -1) {
                        downloadIamge(url, fileName);
                    } else {
                        let a = document.createElement('a');
                        // let filename = ''//record.datumContent;不知道为啥原来的人要把字段注释
                        a.href = url;
                        a.download = url;
                        // a.target = '_blank';
                        // if (record.key.toLowerCase().endsWith('.pdf')) {
                        // }
                        // window.open(url);
                        a.click();
                    }
                } else {
                    danger({ 'text': response.data.exMsg });
                }
            }, error => {
                console.error(error);
            });
    }

    render() {
        let {
            label,
        } = this.props;
        let {
            isShow,
            action,
            uploadInfoData,
            fileList,
        } = this.state;
        return (
            <Modal className='ygc-upload-modal' show={isShow} size={'lg'} onHide={this.closeUpload} backdrop={false}>
                <Modal.Header className='ygc-upload-header' closeButton>
                    <Modal.Title > {label || '附件管理'} </Modal.Title>
                </Modal.Header >
                <Modal.Body>
                    <Dragger {...this.uploadProps}
                        action={action}
                        data={uploadInfoData}>
                        <p className="u-upload-drag-icon">
                            <Icon type="inbox" className="uf-upload" />
                        </p>
                        <p className="u-upload-text">把文件拖入指定区域，完成上传，同样支持点击上传。</p>
                    </Dragger>
                    <div className='filelist-container'>
                        {
                            fileList.map((cur, index) => {
                                let submit = cur.submit;
                                return (<div className='filelist-item' key={cur.uid}>
                                    <div className='filelist-name-row'>
                                        {cur.type == 'image' ?
                                            // <a href={cur.origUrl} target='_blank'>
                                            //     <img src={cur.snapshotUrl} />
                                            // </a>
                                            <a href={cur.origUrl} target='_blank'>
                                                {cur.name}
                                            </a>
                                            :
                                            <span className='file-name'>{cur.name}</span>
                                        }
                                        <Icon title={submit ? '删除' : '取消'}
                                            type="uf-close"
                                            onClick={this.cancelClick.bind(this, cur)} />
                                        {submit && <Icon title='下载' type="uf-cloud-down"
                                            onClick={this.downloadClick.bind(this, cur)} />}
                                    </div>
                                    {!submit &&
                                        <ProgressBar size="sm" now={cur.percent} active></ProgressBar>}
                                </div>);
                            })
                        }
                    </div>
                </Modal.Body>
                {/* <Modal.Footer>
                    <div className="refer-btn-group">
                        <Button className='icon-cancel-btn' onClick={this.closeUpload}> 取消 </Button>
                        <Button colors="primary" onClick={this.sureClick}> 保存 </Button>
                    </div>
                </Modal.Footer> */}
            </Modal>
        )
    }
}

export default YGCCreateUpload;